package cn.slipi.admin.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @author man
 */
public class GsonUtil {

    private final static Logger LOG = LoggerFactory.getLogger(GsonUtil.class);

    private final static Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping().create();


    public static <T> T fromJson(String json, Class<T> classOfT) {
        try {
            return GSON.fromJson(json, classOfT);
        } catch (Exception e) {
            LOG.error("GsonUtil.fromJson异常:", e);
            return BeanUtils.instantiateClass(classOfT);
        }
    }

    public static <T> T fromJson(byte[] charArr, Class<T> classOfT) {
        try {
            return GSON.fromJson(new String(charArr), classOfT);
        } catch (Exception e) {
            LOG.error("GsonUtil.fromJson异常:", e);
            return BeanUtils.instantiateClass(classOfT);
        }
    }

    public static <T> T fromJson(String json, Type type) {
        try {
            return GSON.fromJson(json, type);
        } catch (Exception e) {
            LOG.error("GsonUtil.fromJson异常:", e);
            return null;
        }
    }

    public static String toJson(Object obj) {
        try {
            return GSON.toJson(obj);
        } catch (Exception e) {
            LOG.error("GsonUtil.toJson异常:", e);
            return null;
        }
    }

    public static String toJson(Object obj, String datePattern) {
        try {
            return new GsonBuilder().setDateFormat(datePattern).disableHtmlEscaping().create().toJson(obj);
        } catch (Exception e) {
            LOG.error("GsonUtil.toJson异常:", e);
            return null;
        }
    }

    public static <T> String listToJson(List<T> ts) {
        String jsons = JSON.toJSONString(ts);
        return jsons;
    }

    public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
        @SuppressWarnings("unchecked")
        List<T> ts = JSONArray.parseArray(jsonString, clazz);
        return ts;
    }

}
